#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

from threading import Thread, Event


__all__ = [ "StoppableThread" ]


class StoppableThread( Thread ):
    def __init__( self, sleep_s=0.2, **kwds ):
        Thread.__init__( self, **kwds )
        self._stopevent = Event()
        self._sleep_seconds = sleep_s

    def run( self ):
        '''run() must be implemented in the child class
        doing something like the following

        while not self._stopevent.isSet():
            # work ...
            self._stopevent.wait(self._sleep_seconds)

        '''
        #self.target()
        raise NotImplementedError
    
    def join( self, timeout=None ):
        "join() stops the thread"
        #print "stopping thread", self.getName()
        self._stopevent.set()
        Thread.join( self, timeout )
